package com.fiestas.db;

import java.util.ArrayList;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.fiestas.dao.Socio;

public class DBManager{

	private DBHelper dbHelper;
	private SQLiteDatabase db;
	
	public DBManager(Context context){
		dbHelper = new DBHelper(context, "FIESTASDB", null, 1);
		db = dbHelper.getWritableDatabase();
		if(!db.isReadOnly()){
			dbHelper.updatePragmaRule(db);
		}
	}
	
	public void closeDBConnection(){
		db.close();
	}
	
	public void insertSocio(String name,String surname,String pathImage,Integer password){
		ContentValues newSocio = new ContentValues();
		newSocio.put("name", name);
		newSocio.put("surname", surname);
		newSocio.put("pathImage",pathImage);
		newSocio.put("password", password);
		db.insert("users", null, newSocio);
	}
	public void insertPago(Integer ref, String nameSocio, String name, Double cuantity){
		ContentValues newSocio = new ContentValues();
		newSocio.put("ref", ref);
		newSocio.put("nameSocio", nameSocio);
		newSocio.put("name", name);
		newSocio.put("cuantity",cuantity);
		
		db.insert("payments", null, newSocio);
	}
	
	public void updateRowQuery(String tableName, ContentValues updatedRowContents, String whereClause){
		db.update(tableName, updatedRowContents, whereClause, null);
	}
	
	public void deleteRowQuery(String tableName, String whereClause){
		db.delete(tableName, whereClause, null);
	}
	
	public String queryPassword(String nameSocio){
		String result = "";
		String query = "SELECT password from users where name = '" + nameSocio + "'";
		Cursor cursor = db.rawQuery(query, null);
		if(cursor.moveToFirst()){
			do {
				Socio socio = new Socio();
				socio.setPassword(cursor.getString(0));
				result = socio.getPassword();
			} while (cursor.moveToNext());
		}
		
		
		return result;
	}
	public ArrayList<Socio> getAllMembers() {
	    ArrayList<Socio> memberList = new ArrayList<Socio>();
	    // Select All Query
	    String selectQuery = "SELECT * FROM users ORDER BY name COLLATE NOCASE" ;
	    Cursor cursor = db.rawQuery(selectQuery, null);
	 
	    // looping through all rows and adding to list
	    if (cursor.moveToFirst()) {
	        do {
	            Socio member = new Socio();
	            member.setName(cursor.getString(0));
	            member.setSurname(cursor.getString(1));
	            member.setPathImage(cursor.getString(2));
	            member.setPassword(cursor.getString(3));
	             // Adding member to list
	            memberList.add(member);
	        } while (cursor.moveToNext());
	    }	    
	    // return user list
	    return memberList;
	    
	}
}
